import React from 'react';
import Taro from '@tarojs/taro';
import { View, Image, Text, Button, Input } from '@tarojs/components'
import { AtForm, AtButton, AtToast } from 'taro-ui'
import { countDown, isPhone, isCode, trimAll } from '@/utils/index'
import { connect } from 'react-redux'
import { userAuth, aliPayUserAuth } from '@/store/user/action'
import { getVerifieCode, wxUserInfo } from '@/api/user'
const carLogoImg = 'https://static3.jekunauto.com/img/others/car-logo.png'
const cariconImg = 'https://static3.jekunauto.com/img/others/car-icon2.png'
import { getSessionKey } from '@/api/user/index'
import { aliPayUserInfo, getAliPayMobile } from '@/api/user'
import { getAuthCode } from '@/utils/auth'
import Authorization from '@/components/Authorization'
import './index.scss'

interface State {
  mode: number
  userPhone: string
  code: string
  tipsText: string
  tipsIsOpened: boolean
  codeStatus: boolean
  timeCount: string
  phoneLoing: boolean
	isOpen:boolean
}

const TIMECOUNT = 60

interface Props {
  distributionUserId?: any
  value?: boolean
}
@connect<any>(({ user }) => ({ user }), dispatch => ({
  setUserAuth(params: object) {
    return new Promise((resolve) => {
      const state = userAuth(params)
      dispatch(state)
      resolve(params)
    })
  },
  setAliPayUserAuth(params: object) {
    return new Promise((resolve) => {
      const state = aliPayUserAuth(params)
      dispatch(state)
      resolve(params)
    })
  }
}))
class UserLoginView extends React.Component<any> {
  constructor (props) {
    super(props)
    this.state = {
      mode: 0, // 登录方式 0微信 1手机号
      userPhone: '',// 手机号
      code: '',// 验证码
      tipsText: '',// 轻提示内容
      tipsIsOpened: false,// 是否显示轻提示
      codeStatus: false,
      timeCount: TIMECOUNT + 's',// 验证码倒计时
      phoneLoing: false,
			isOpen:false
    }
  }
  state: State
  // 输入的手机号
  changePhone = (e) => {
    this.setState({
      userPhone: e.detail.value
    })
    return e.detail.value
  }
  // 输入的验证码
  changeCode = (e) => {
    this.setState({
      code: e.detail.value
    })
    return e.detail.value
  }
  // 获取手机号
  getphone = (e: any) => {
    console.log('this----执行有没有', this)
    console.log('this.props', this)
    const { encryptedData, errMsg, iv } = e.detail
    if (errMsg === 'getPhoneNumber:ok') {
      const { setUserAuth, distributionUserId } = this.props
      setUserAuth({
        encryptedData, iv, distributionUserId
      })
    }
  }

  // 获取支付宝小程序用户信息
  onGetAuthorize = () => {
    console.log('执行了吗')
    const { setAliPayUserAuth } = this.props
    console.log('this.props', this.props)
    my.getPhoneNumber({
      success: (res) => {
        let encryptedData = JSON.parse(res.response)
        console.log('encryptedData.response', encryptedData.response)
        getAliPayMobile({
          content: encryptedData.response
        }).then(resp => {
          let { mobile } = resp.data.data
          console.log('mobile', mobile)
          let authCode = Taro.getStorageSync('AUTH_CODE')
          console.log('authCode', authCode)
          aliPayUserInfo({
            authCode
          }).then(res => {
            console.log('有没有执行到这儿来', res)
            let data = res.data.data
            let { aliPayUserId } = data
            console.log('aliPayUserId', aliPayUserId)
            setAliPayUserAuth({
              mobile,
              aliPayUserId
            })
            console.log('data', data)
          }).catch(err => {
            console.log('err', err)
          })
        })
      },
      fail: (res) => {
        console.log(res);
        console.log('getPhoneNumber_fail');
      },
    });
  }

  onAuthError = () => {
    console.log('报错---')
  }

	nextGetUserProfile = ()=>{
		Taro.getUserProfile({
			desc: '获取用户信息',
			success: (res) => {
				// 拿到用户信息，调取接口2，将OpenId与返回的数据关联在一起，并且保存
				// 成功关联之后，记录信息
				const { encryptedData, iv } = res
				const isFromScene: boolean = !!Taro.getStorageSync('STORE_QRCODE')
				wxUserInfo({
					encryptedData,
					iv,
					sessionKey: Taro.getStorageSync('IS_SESSIONKEY'),
					scene: isFromScene,
					openId: Taro.getStorageSync('IS_OPENID')
				}).then((respon) => {
					let data = respon ? respon.data.data : {}
					let { userId } = data
					if (userId) { // 新用户的话，证明用户信息都是无效的，无须保存记录
						Taro.setStorageSync('IS_USERINFO', data)
					}
					this.setState({
						phoneLoing: true
					})
				})
			}
		})
		// 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
	}

  // 获取微信小程序用户信息
  getUserProfile = async () => {
    if (!this.props.value) {
      Taro.showToast({
        title: '请先仔细阅读并勾选同意集群车宝协议!',
        icon: 'none',
        duration: 2000
      })
      return
    }
		if(wx.getPrivacySetting){
			wx.getPrivacySetting({
				success: res => {
					console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
					console.log('res',res)
					if (res.needAuthorization) {
						// 需要弹出隐私协议
						this.setState({
							isOpen: true
						})
					} else {
						this.setState({
							isOpen: false
						})
						this.nextGetUserProfile()
						console.log('执行了没有getUserProfilegetUserProfilegetUserProfile')


					}
				},
				fail: () => {},
				complete: () => {}
			})
		}else{
			this.nextGetUserProfile()
		}
  }

  // 获取验证码
  getCode = (e: any, _type: number = 1) => {
    let { codeStatus, userPhone } = this.state
    if (!userPhone.length) {
      this.setState({
        tipsText: '手机号码不能为空',
        tipsIsOpened: true
      })
      return
    }
    if (!isPhone(userPhone)) {
      this.setState({
        tipsText: '请输入正确的手机号码',
        tipsIsOpened: true
      })
      return
    }
    if (codeStatus) return
    countDown(TIMECOUNT, (n: number) => {
      let setState: object
      if (n === TIMECOUNT) {
        setState = {
          codeStatus: true,
          timeCount: `${n}s`
        }
      } else {
        if (n === 0) {
          setState = {
            codeStatus: false,
            timeCount: `${n}s`
          }
        } else {
          setState = {
            timeCount: `${n}s`
          }
        }
      }
      this.setState(setState)
    })
    // getcode code as this
    getVerifieCode({
      mobile: userPhone,
      type: _type,
      act: 1
    }).then(res => {
      if (res.data.success) {
        Taro.showToast({
          icon: 'none',
          title: _type === 1 ? '验证码已发送，请查看短信' : '验证码将通过语音电话通知，请留意接听'
        })
      }
    })
  }
  //  登录
  async alipayLogin() {
    let { userPhone, code } = this.state
    userPhone = trimAll(userPhone)
    code = trimAll(code)
    if (!isPhone(userPhone)) {
      this.setState({
        tipsText: '请输入正确的手机号码',
        tipsIsOpened: true
      })
      return
    }
    if (!userPhone.length) {
      this.setState({
        tipsText: '手机号码不能为空',
        tipsIsOpened: true
      })
      return
    }
    if (!isCode(code)) {
      this.setState({
        tipsText: '请输入正确的验证码',
        tipsIsOpened: true
      })
      return
    }
    const { setUserAuth } = this.props
    await getAuthCode()
    let authCode = Taro.getStorageSync('AUTH_CODE')
    console.log('authCode', authCode)
    aliPayUserInfo({
      authCode
    }).then(res => {
      let data = res.data.data
      let { aliPayUserId } = data
      console.log('data--------------data', data)
      setUserAuth({
        mobile: userPhone,
        sms: code,
        aliPayUserId
      })
      console.log('data', data)
    })

  }
  //  登录
  async goLogin() {
    let { userPhone, code } = this.state
    console.log('this-----this', this)
    userPhone = trimAll(userPhone)
    code = trimAll(code)

    if (!isPhone(userPhone)) {
      this.setState({
        tipsText: '请输入正确的手机号码',
        tipsIsOpened: true
      })
      return
    }
    if (!userPhone.length) {
      this.setState({
        tipsText: '手机号码不能为空',
        tipsIsOpened: true
      })
      return
    }
    if (!isCode(code)) {
      this.setState({
        tipsText: '请输入正确的验证码',
        tipsIsOpened: true
      })
      return
    }
    if (!this.props.value) {
      Taro.showToast({
        title: '请先仔细阅读并勾选同意集群车宝协议!',
        icon: 'none',
        duration: 2000
      })
      return
    }


    // login code as this
    const { setUserAuth, distributionUserId } = this.props

    // 获取openId 后登录
    if (Taro.getStorageSync('IS_OPENID')) {
      setUserAuth({
        mobile: userPhone,
        sms: code,
        openid: Taro.getStorageSync('IS_OPENID'),
        distributionUserId
      })
    } else {
      try {
        const resulte = await Taro.login()
        const resInfo: any = await getSessionKey({
          code: resulte.code
        })
        if (resInfo.data.success) {
          const data = resInfo.data.data
          setUserAuth({
            mobile: userPhone,
            sms: code,
            openid: data.openId,
            distributionUserId
          })
        } else {
          this.setState({
            tipsText: '获取用户信息失败，请稍后重试',
            tipsIsOpened: true
          })
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
  //切换微信，手机号登录
  setMode = () => {
    const { mode } = this.state
    this.setState({
      mode: mode === 1 ? 0 : 1,
    })
  }
  isWxPhoneView() {
    const { phoneLoing,isOpen} = this.state
    return (
      <View>
        <View className='user-login__imgview'>
          <Image className='user-login__car-logo' src={carLogoImg} />
          <Image className='user-login__imgplugin' src={cariconImg} />
          <View className='user-login__title'><Text className='user-login__title--text'>享受福利</Text>轻松养车</View>
        </View>
        <View className='user-login__group'>
          {
            process.env.TARO_ENV === 'weapp' ?
              <Button onClick={this.getUserProfile} className='btn-max-w' plain type='primary'>
                {/* <Iconfont size='44' color='#09BB07' name='icon-weixin' /> */}
                授权用户信息登录
              </Button> :
              <button open-type="getAuthorize"
                onGetAuthorize={this.onGetAuthorize} onError={this.onAuthError} scope='phoneNumber'>
                支付宝授权用户信息登录
              </button>
            // <Button open-type="getAuthorize"  scope='phoneNumber' className='btn-max-w' plain type='primary'>
            // 		支付宝授权用户信息登录
            // </Button>
          }
          <View className='user-login__group--text' onClick={this.setMode}>使用手机号码登录</View>

        </View>
        {
          phoneLoing ? (
            <View className="user-login__dialog">
              <View className="user-login__dialog--mask"></View>
              <View className="user-login__dialog--content">
                <View className="user-login__dialog--title">提示</View>
                <View className="user-login__dialog--graph">请使用手机号码登录~</View>
                <Button openType='getPhoneNumber' onGetPhoneNumber={this.getphone} className='btn-max-w' type='primary'>
                  手机号快捷登录
                </Button>
              </View>
            </View>
          ) : null
        }

			<Authorization isOpen={isOpen}></Authorization>
      </View>
    )
  }

  isImportPhoneView() {
    const { tipsIsOpened, tipsText, userPhone, code, codeStatus, timeCount } = this.state
    return (
      <View>
        {/* 轻提示 */}
        <AtToast onClose={() => {
          this.setState({
            tipsText: '',
            tipsIsOpened: false
          })
        }} isOpened={tipsIsOpened} text={tipsText} icon='alert-circle'
        ></AtToast>
        <Image className='user-login__car-logo2' src={carLogoImg} />
        <View className='user-login__import'>
          <AtForm>
            <View className='self-inp-box'>
              <Input
                placeholderStyle={'color:#999'}
                placeholder='请输入手机号'
                name='userphone'
                value={this.state.userPhone}
                maxlength={11}
                onInput={this.changePhone}
              />
            </View>
            <View className='self-inp-box'>
              <Input
                maxlength={5}
                placeholderStyle={'color:#999'}
                name='code'
                onInput={this.changeCode}
                value={this.state.code}
                placeholder='输入验证码'
              >
              </Input>
              <View
                onClick={this.getCode}
                className={
                  userPhone ? 'user-login__getcode' : 'user-login__getcode disable'
                }
              >
                {codeStatus ? timeCount : '获取验证码'}
              </View>
            </View>
          </AtForm>
        </View>
        <View className='user-login__flex-right'>
          无法获取验证码？试下<Text onClick={e => this.getCode(e, 2)} className='user-login__audio'>语音验证</Text>
        </View>
        <View className='user-login__group'>
          {
            process.env.TARO_ENV === 'weapp' ?
              <AtButton type='primary' onClick={this.goLogin.bind(this)} disabled={!userPhone && !code.length}>登录</AtButton>
              :
              <AtButton type='primary' onClick={this.alipayLogin.bind(this)} disabled={!userPhone && !code.length}>登录</AtButton>
          }
          <View className='user-login__group--text' onClick={this.setMode}>{`使用${process.env.TARO_ENV === 'weapp' ? '微信' : '支付宝'}登录`}</View>
        </View>
      </View>
    )
  }

  render() {
    const { mode } = this.state
    return (
      <View className='user-login'>
        {mode === 0 ? this.isWxPhoneView() : this.isImportPhoneView()}
      </View>
    )
  }
}

export default UserLoginView
